package org.gitos.cloud.server.mq.logic;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.gitos.cloud.domain.comm.Constant;
import org.gitos.cloud.domain.mq.MqMsg;
import org.gitos.cloud.domain.tcp.Bucket;
import org.gitos.cloud.server.mq.PushManager;
import org.gitos.cloud.util.HexUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * Created by shizhengchu on 16/3/23.
 */
public class ApplyAuthHandler implements Runnable {
    private static Logger log = LoggerFactory.getLogger(ApplyAuthHandler.class);


    private MqMsg msg;
    private PushManager pushManager;
    private String channleId;
    private String nodeId;
    private StringRedisTemplate stringRedisTemplate;

    public MqMsg getMsg() {
        return msg;
    }

    public void setMsg(MqMsg msg) {
        this.msg = msg;
    }

    public PushManager getPushManager() {
        return pushManager;
    }

    public void setPushManager(PushManager pushManager) {
        this.pushManager = pushManager;
    }

    public String getNodeId() {
        return nodeId;
    }

    public void setNodeId(String nodeId) {
        this.nodeId = nodeId;
    }

    public String getChannleId() {
        return channleId;
    }

    public void setChannleId(String channleId) {
        this.channleId = channleId;
    }

    public ApplyAuthHandler(MqMsg msg) {
        this.msg = msg;
    }

    public StringRedisTemplate getStringRedisTemplate() {
        return stringRedisTemplate;
    }

    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public void run() {
        String authCodeStr = generateAuthCodeOfNum(16);
        byte[] authCode = HexUtil.decodeHex(authCodeStr.toCharArray());
        MqMsg return_msg = new MqMsg();
        return_msg.setChannelId(channleId);
        return_msg.setNodeId(nodeId);
        Bucket bucket = new Bucket();
        bucket.setCmd(Constant.CMD_DOWN_AUTH_CODE);
        bucket.setContent(authCode);
        bucket.setDeviceId(msg.getBucket().getDeviceId());
        return_msg.setBucket(bucket);
        stringRedisTemplate.opsForValue().set(channleId, HexUtil.encodeHexStr(authCode), 10, TimeUnit.DAYS);
        pushManager.sendMsg(return_msg.getNodeId(), return_msg);
    }

    public static String generateAuthCodeOfNum(int length) {
        String NUM[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(NUM[random.nextInt(NUM.length)]);
        }
        return sb.toString();
    }
}
